package com.example.demo.service;

import com.example.demo.entity.Admin;
import com.example.demo.entity.User;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.AdminMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.dto.UserQueryDTO;
import com.example.demo.param.UserUpdateParam;
import com.example.demo.util.UserConverter;
import com.example.demo.vo.LoginVO;
import com.example.demo.vo.UserVO;
import com.example.demo.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员服务类
 * 
 * @author zhang
 * @date 2024
 */
@Service
public class AdminService {
    
    private static final Logger logger = LoggerFactory.getLogger(AdminService.class);
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 管理员登录
     * 校验管理员状态，禁用管理员无法登录
     */
    public LoginVO login(String username, String password) {
        Admin admin = adminMapper.findByUsername(username);
        if (admin == null) {
            throw new BusinessException(401, "用户名或密码错误");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, admin.getPassword())) {
            throw new BusinessException(401, "用户名或密码错误");
        }
        
        // 检查管理员状态（0-禁用，1-启用）
        if (admin.getStatus() == null || admin.getStatus() == 0) {
            logger.warn("管理员已被禁用: {}", username);
            throw new BusinessException(403, "管理员已被禁用，无法登录");
        }
        
        logger.info("管理员登录成功: {}", username);
        return buildAdminLoginVO(admin);
    }
    
    /**
     * 构建管理员登录VO
     */
    private LoginVO buildAdminLoginVO(Admin admin) {
        // 生成Token
        String token = jwtUtil.generateToken(admin.getId(), admin.getUsername());
        
        // 构建响应
        LoginVO vo = new LoginVO();
        vo.setToken(token);
        vo.setTokenType("Bearer");
        
        LoginVO.UserInfoVO userInfo = new LoginVO.UserInfoVO();
        userInfo.setId(admin.getId());
        userInfo.setUsername(admin.getUsername());
        userInfo.setNickname(admin.getRealName());
        userInfo.setEmail(admin.getEmail());
        vo.setUserInfo(userInfo);
        
        return vo;
    }
    
    /**
     * 查询用户列表
     */
    public List<UserVO> queryUsers(UserQueryDTO dto) {
        // 计算分页参数
        if (dto.getPageNum() == null || dto.getPageNum() <= 0) {
            dto.setPageNum(1);
        }
        if (dto.getPageSize() == null || dto.getPageSize() <= 0) {
            dto.setPageSize(10);
        }
        int offset = (dto.getPageNum() - 1) * dto.getPageSize();
        
        // 保存原始页码，设置偏移量用于SQL查询
        Integer originalPageNum = dto.getPageNum();
        dto.setPageNum(offset);
        
        List<User> users = userMapper.queryUsers(dto);
        
        // 恢复原始页码
        dto.setPageNum(originalPageNum);
        
        return users.stream()
                .map(UserConverter::toVO)
                .collect(Collectors.toList());
    }
    
    /**
     * 统计用户总数
     */
    public long countUsers(UserQueryDTO dto) {
        return userMapper.countUsers(dto);
    }
    
    /**
     * 更新用户信息
     */
    public void updateUser(UserUpdateParam param) {
        User user = userMapper.findById(param.getId());
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }
        
        // 更新字段
        if (param.getNickname() != null) {
            user.setNickname(param.getNickname());
        }
        if (param.getEmail() != null) {
            user.setEmail(param.getEmail());
        }
        if (param.getPhone() != null) {
            user.setPhone(param.getPhone());
        }
        if (param.getStatus() != null) {
            user.setStatus(param.getStatus());
        }
        
        userMapper.update(user);
    }
}

